package com.zhupf.binaryTree;

/**
 * @author zhupf
 * @date 2023年12月04日 9:59
 * @Description
 *
 *  114、二叉树展开为链表
 */
public class Flatten {

    public static void main(String[] args) {
        Flatten fa = new Flatten();
        TreeNode root = new TreeNode(1,new TreeNode(2,new TreeNode(3),new TreeNode(4)),new TreeNode(5,null,new TreeNode(6)));
        fa.flatten(root);
    }

    public void flatten(TreeNode root) {
        TreeNode pre = new TreeNode(0);
        pre.right = root;
        this.process(root);
    }
    public TreeNode process(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode left = this.process(root.left);
        TreeNode right = this.process(root.right);
        if(left != null){
            root.left = null;
            root.right = left;
            while (left.right != null){
                left = left.right;
            }
            left.right = right;
        }
        return root;
    }

    public void flatten2(TreeNode root) {
        while (root != null){
            if(root.left == null){
                root = root.right;
            }else {
                TreeNode left = root.left;
                TreeNode right = root.right;
                root.right = left;
                while (left.right != null){
                    left = left.right;
                }
                root.left = null;
                left.right = right;
                root = root.right;
            }
        }
    }

    TreeNode pre = null;

    public void flatten3(TreeNode root) {
        if(root == null){
            return;
        }
        flatten3(root.right);
        flatten3(root.left);
        root.right = pre;
        root.left = null;
        pre = root;
    }

}
